package com.huyframe.model.manager;

import android.util.Log;

import com.github.lazylibrary.util.NetWorkUtils;
import com.huyframe.config.OkHttpConfig;
import com.huyframe.utils.ACache;
import com.huyframe.utils.AndroidKit;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import com.squareup.okhttp.internal.framed.Header;

import java.io.IOException;
import java.net.CookieHandler;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okio.BufferedSource;

/**
 * Created by BillLamian on 2016/7/14.
 */
public class OkHttpManager {

    private static final String TAG="HuyFrame";
    private static OkHttpClient okHttpClient;
    public static OkHttpClient getInstance(){
        if(okHttpClient==null){
            synchronized (OkHttpManager.class){
                if(okHttpClient==null){
                    okHttpClient=new OkHttpClient();
                    okHttpClient.setCache(new Cache(OkHttpConfig.CACHE_DIR,OkHttpConfig.CACHE_SIZE));
                    okHttpClient.setConnectTimeout(OkHttpConfig.CONNECTIONTIMEOUT, TimeUnit.SECONDS);
                    okHttpClient.interceptors().add(CACHE_INTERCEPTOR);
                }
            }
        }
        return okHttpClient;
    }



     static Interceptor CACHE_INTERCEPTOR=new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request=chain.request();
            if (NetWorkUtils.getNetworkTypeName(AndroidKit.getContext()).equals(NetWorkUtils.NETWORK_TYPE_DISCONNECT)) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }
            Response response=chain.proceed(request);
            ACache aCache=ACache.get(AndroidKit.getContext());
            if(NetWorkUtils.getNetworkTypeName(AndroidKit.getContext()).equals(NetWorkUtils.NETWORK_TYPE_DISCONNECT)){//没网
                int maxStale = 60 * 60 * 24 * 28; // 无网络时，设置超时为4周
                response.newBuilder()
                .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                .removeHeader("Pragma").build();
            }else{
                int maxAge = 60*2; // 有网络时 设置缓存超时时间2min
                response.newBuilder()
                .header("Cache-Control", "public, max-age=" + maxAge)
                .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                .build();

            }
            return response;
        }
    };



//    static Interceptor LOG_INTERCEPTOR=new Interceptor() {
//        @Override
//        public Response intercept(Chain chain) throws IOException {
//            long startTime = System.currentTimeMillis();
//            Log.v("TAG",String.format("%s-URL: %s %n",chain.request().method(),
//                    chain.request().url()));
//            Response res = chain.proceed(chain.request());
//            long endTime = System.currentTimeMillis();
//            Log.v("TAG",String.format("CostTime: %.1fs", (endTime-startTime) / 1000.0));
//            return res;
//        }
//    };

}
